package com.wowangz.cms.common.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class FileTools {

	// 删除指定文件夹下所有文件
	// param path 文件夹完整绝对路径
	public static boolean delAllFile(String path) {
		boolean flag = false;
		File file = new File(path);
		if (!file.exists()) {
			return flag;
		}
		if (!file.isDirectory()) {
			return flag;
		}
		String[] tempList = file.list();
		File temp = null;
		for (String element : tempList) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + element);
			} else {
				temp = new File(path + File.separator + element);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + element);// 先删除文件夹里面的文件
				delFolder(path + "/" + element);// 再删除空文件夹
				flag = true;
			}
		}
		return flag;
	}

	// 删除文件夹
	// param folderPath 文件夹完整绝对路径
	public static void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // 删除完里面所有内容
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			myFilePath.delete(); // 删除空文件夹
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * / 转换文件大小
	 * 
	 * @param fileS
	 * @return
	 */
	public static String formetFileSize(long fileS) {
		DecimalFormat df = new DecimalFormat("#.00");
		String fileSizeString = "";
		if (fileS < 1024) {
			fileSizeString = df.format((double) fileS) + "B";
		} else if (fileS < 1048576) {
			fileSizeString = df.format((double) fileS / 1024) + "K";
		} else if (fileS < 1073741824) {
			fileSizeString = df.format((double) fileS / 1048576) + "M";
		} else {
			fileSizeString = df.format((double) fileS / 1073741824) + "G";
		}
		return fileSizeString;
	}

	/**
	 * 获取文件扩展名
	 * 
	 * @param file
	 * @return
	 */
	public static String getFileExtension(String fileName) {
		if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
			return fileName.substring(fileName.lastIndexOf(".") + 1);
		} else {
			return "";
		}
	}

	// 递归 获取文件夹的的大小
	public static long getFileSize(File f) throws Exception {
		long size = 0;
		File flist[] = f.listFiles();
		for (File element : flist) {
			if (element.isDirectory()) {
				size = size + getFileSize(element);
			} else {
				size = size + element.length();
			}
		}
		return size;
	}

	/**
	 * 获取文件的大小
	 * 
	 * @param f
	 * @return
	 * @throws Exception
	 */
	public static long getFileSizes(File f) throws Exception {// 取得文件大小
		long s = 0;
		FileInputStream fis = null;
		try {
			if (f.exists()) {
				fis = new FileInputStream(f);
				s = fis.available();
			} else {
				f.createNewFile();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if (fis != null) {
					fis.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return s;
	}

	/**
	 * 获得文件的后缀名
	 * 
	 * @param fileUri
	 * @return
	 */
	public static String getFileType(String fileUri) {
		File file = new File(fileUri);
		String fileName = file.getName();
		String fileType = fileName.substring(fileName.lastIndexOf(".\\") + 1, fileName.length());
		return fileType;
	}

	/**
	 * 获取文件夹的个数
	 * 
	 * @param f
	 * @return
	 */
	public static long getlist(File f) {// 递归求取目录文件个数
		long size = 0;
		File flist[] = f.listFiles();
		size = flist.length;
		for (File element : flist) {
			if (element.isDirectory()) {
				size = size + getlist(element);
				size--;
			}
		}
		return size;

	}

	/**
	 * 使用文件通道的方式复制文件
	 * 
	 * @param s
	 *            源文件
	 * @param t
	 *            复制到的新文件
	 */
	public void fileChannelCopy(File s, File t) {
		FileInputStream fi = null;
		FileOutputStream fo = null;
		FileChannel in = null;
		FileChannel out = null;
		try {
			fi = new FileInputStream(s);
			fo = new FileOutputStream(t);
			in = fi.getChannel();// 得到对应的文件通道
			out = fo.getChannel();// 得到对应的文件通道
			in.transferTo(0, in.size(), out);// 连接两个通道，并且从in通道读取，然后写入out通道
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(out!=null)
				{
					out.close();
				}
				if(in!=null)
				{
					in.close();
				}
				if(fo!=null)
				{
					fo.close();
				}
				if(fi!=null)
				{
					fi.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	/**
	 * 根据地址获得数据的字节流
	 * 
	 * @param strUrl
	 *            网络连接地址
	 * @return
	 */
	public static byte[] getInputStreamByNetUrl(String strUrl) {
		HttpURLConnection conn=null;
		InputStream inStream=null;
		try {
			URL url = new URL(strUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5 * 1000);
			inStream = conn.getInputStream();// 通过输入流获取图片数据
			byte[] bytes = readInputStream(inStream);// 得到图片的二进制数据
			return bytes;
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(inStream!=null){
				try {
					inStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(conn!=null){
				conn.disconnect();
			}
		}
		return null;
	}

	/**
	 * 从输入流中获取数据
	 * 
	 * @param inStream
	 *            输入流
	 * @return
	 * @throws Exception
	 */
	public static byte[] readInputStream(InputStream inStream) throws Exception {
		byte[] returnbytes=null;
		ByteArrayOutputStream outStream=null;
		try{
			outStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inStream.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
			}
			returnbytes = outStream.toByteArray();
		}
		catch(Exception e){
			e.printStackTrace();
			throw e;
		}
		finally{
			if(outStream!=null){
				outStream.close();
			}
		}
		return returnbytes;
	}
	
	//文件类型集合
	public final static Map<String, String> FILE_TYPE_MAP = new HashMap<String, String>();
	static{       
        getAllFileType(); //初始化文件类型信息       
    } 
	/**    
     * Discription:[getAllFileType,常见文件头信息]  
     */       
    private static void getAllFileType() {       
        FILE_TYPE_MAP.put("ffd8ffe000104a464946", "jpg"); //JPEG (jpg)       
        FILE_TYPE_MAP.put("89504e470d0a1a0a0000", "png"); //PNG (png)       
        FILE_TYPE_MAP.put("47494638396126026f01", "gif"); //GIF (gif)       
        FILE_TYPE_MAP.put("49492a00227105008037", "tif"); //TIFF (tif)       
        FILE_TYPE_MAP.put("424d228c010000000000", "bmp"); //16色位图(bmp)       
        FILE_TYPE_MAP.put("424d8240090000000000", "bmp"); //24位位图(bmp)       
        FILE_TYPE_MAP.put("424d8e1b030000000000", "bmp"); //256色位图(bmp)       
        FILE_TYPE_MAP.put("41433130313500000000", "dwg"); //CAD (dwg)       
        FILE_TYPE_MAP.put("3c21444f435459504520", "html"); //HTML (html)  
        FILE_TYPE_MAP.put("3c21646f637479706520", "htm"); //HTM (htm)  
        FILE_TYPE_MAP.put("48544d4c207b0d0a0942", "css"); //css  
        FILE_TYPE_MAP.put("696b2e71623d696b2e71", "js"); //js  
        FILE_TYPE_MAP.put("7b5c727466315c616e73", "rtf"); //Rich Text Format (rtf)       
        FILE_TYPE_MAP.put("38425053000100000000", "psd"); //Photoshop (psd)       
        FILE_TYPE_MAP.put("46726f6d3a203d3f6762", "eml"); //Email [Outlook Express 6] (eml)         
        FILE_TYPE_MAP.put("d0cf11e0a1b11ae10000", "doc"); //MS Excel 注意：word、msi 和 excel的文件头一样       
        FILE_TYPE_MAP.put("d0cf11e0a1b11ae10000", "vsd"); //Visio 绘图       
        FILE_TYPE_MAP.put("5374616E64617264204A", "mdb"); //MS Access (mdb)        
        FILE_TYPE_MAP.put("252150532D41646F6265", "ps");       
        FILE_TYPE_MAP.put("255044462d312e350d0a", "pdf"); //Adobe Acrobat (pdf)     
        FILE_TYPE_MAP.put("2e524d46000000120001", "rmvb"); //rmvb/rm相同    
        FILE_TYPE_MAP.put("464c5601050000000900", "flv"); //flv与f4v相同    
        FILE_TYPE_MAP.put("00000020667479706d70", "mp4");   
        FILE_TYPE_MAP.put("49443303000000002176", "mp3");   
        FILE_TYPE_MAP.put("000001ba210001000180", "mpg"); //       
        FILE_TYPE_MAP.put("3026b2758e66cf11a6d9", "wmv"); //wmv与asf相同      
        FILE_TYPE_MAP.put("52494646e27807005741", "wav"); //Wave (wav)    
        FILE_TYPE_MAP.put("52494646d07d60074156", "avi");    
        FILE_TYPE_MAP.put("4d546864000000060001", "mid"); //MIDI (mid)     
        FILE_TYPE_MAP.put("504b0304140000000800", "zip");      
        FILE_TYPE_MAP.put("526172211a0700cf9073", "rar");     
        FILE_TYPE_MAP.put("235468697320636f6e66", "ini");     
        FILE_TYPE_MAP.put("504b03040a0000000000", "jar");   
        FILE_TYPE_MAP.put("4d5a9000030000000400", "exe");//可执行文件  
        FILE_TYPE_MAP.put("3c25402070616765206c", "jsp");//jsp文件  
        FILE_TYPE_MAP.put("4d616e69666573742d56", "mf");//MF文件  
        FILE_TYPE_MAP.put("3c3f786d6c2076657273", "xml");//xml文件  
        FILE_TYPE_MAP.put("494e5345525420494e54", "sql");//xml文件  
        FILE_TYPE_MAP.put("7061636b616765207765", "java");//java文件  
        FILE_TYPE_MAP.put("406563686f206f66660d", "bat");//bat文件  
        FILE_TYPE_MAP.put("1f8b0800000000000000", "gz");//gz文件  
        FILE_TYPE_MAP.put("6c6f67346a2e726f6f74", "properties");//bat文件  
        FILE_TYPE_MAP.put("cafebabe0000002e0041", "class");//bat文件  
        FILE_TYPE_MAP.put("49545346030000006000", "chm");//bat文件  
        FILE_TYPE_MAP.put("04000000010000001300", "mxp");//bat文件  
        FILE_TYPE_MAP.put("504b0304140006000800", "docx");//docx文件  
        FILE_TYPE_MAP.put("d0cf11e0a1b11ae10000", "wps");//WPS文字wps、表格et、演示dps都是一样的  
        FILE_TYPE_MAP.put("6431303a637265617465", "torrent");  
          
            
        FILE_TYPE_MAP.put("6D6F6F76", "mov"); //Quicktime (mov)    
        FILE_TYPE_MAP.put("FF575043", "wpd"); //WordPerfect (wpd)     
        FILE_TYPE_MAP.put("CFAD12FEC5FD746F", "dbx"); //Outlook Express (dbx)       
        FILE_TYPE_MAP.put("2142444E", "pst"); //Outlook (pst)        
        FILE_TYPE_MAP.put("AC9EBD8F", "qdf"); //Quicken (qdf)       
        FILE_TYPE_MAP.put("E3828596", "pwl"); //Windows Password (pwl)           
        FILE_TYPE_MAP.put("2E7261FD", "ram"); //Real Audio (ram)       
    } 
	
    /** 
     * 得到上传文件的文件头 
     * @param src 
     * @return 
     */  
    public static String bytesToHexString(byte[] src) {  
        StringBuilder stringBuilder = new StringBuilder();  
        if (src == null || src.length <= 0) {  
            return null;  
        }  
        for (int i = 0; i < src.length; i++) {  
            int v = src[i] & 0xFF;  
            String hv = Integer.toHexString(v);  
            if (hv.length() < 2) {  
                stringBuilder.append(0);  
            }  
            stringBuilder.append(hv);  
        }  
        return stringBuilder.toString();  
    }  
      
    /** 
     * 获得拦截的文件的后缀
     * 根据制定文件的文件头判断其文件类型 
     * @param filePaht 
     * @return 
     */  
    public static String getInterceptorFileType(InputStream stream){  
        String res = null;  
        try {  
            byte[] b = new byte[10];  
            stream.read(b, 0, b.length);  
            String fileCode = bytesToHexString(b);    
            System.out.println(fileCode);  
            //这种方法在字典的头代码不够位数的时候可以用但是速度相对慢一点  
            Iterator<String> keyIter = FILE_TYPE_MAP.keySet().iterator();  
            while(keyIter.hasNext()){  
                String key = keyIter.next();  
                if(key.toLowerCase().startsWith(fileCode.toLowerCase()) || fileCode.toLowerCase().startsWith(key.toLowerCase())){  
                    res = FILE_TYPE_MAP.get(key);  
                    break;  
                }  
            }  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } 
        return res;  
    }  
    
    /**
     * 转化成集合
     * @param value
     * @return
     */
    public static List<String> asArray(String value) {
    	List<String> array = new ArrayList<String>();
    	if (value != null) {
			String[] vals = value.split(",");
			for (String string : vals) {
				array.add(string);
			}
		}
    	return array;
    }
    
    /**
     * 判断是否存在需要过滤的文件后缀
     * @param systemConfigMap
     * @param suffix
     * @return
     */
    public static boolean isVarabled(Map<String, Object> systemConfigMap, String suffix) {
		Set<String> sets = systemConfigMap.keySet();
		for (Iterator<String> iterator = sets.iterator(); iterator.hasNext();) {
			String string = (String) iterator.next();
			if (org.apache.commons.lang3.StringUtils.isNotEmpty(string)) {
				List<String> list = FileTools.asArray(systemConfigMap.get(string).toString());
				if (list.contains(suffix)) {
					return true;
				}
			}
		}
		return false;
	}

    /**
     * 将需要过滤的后缀组合成字符串
     * @param systemConfigMap
     * @return
     */
    public static String getString(Map<String, Object> systemConfigMap) {
		String strings = "";
		Set<String> sets = systemConfigMap.keySet();
		for (Iterator<String> iterator = sets.iterator(); iterator.hasNext();) {
			String string = (String) iterator.next();
			if (org.apache.commons.lang3.StringUtils.isNotEmpty(string)) {
				strings += systemConfigMap.get(string).toString() + ",";
			}
		}
		return org.apache.commons.lang3.StringUtils.isNotEmpty(strings) == true ? strings.substring(0, strings.length() - 1) : strings;
	}
}
